<?php

class RestRouter extends Zend_Controller_Router_Rewrite 
{
    /**
     * Find a matching route to the current PATH_INFO and inject
     * returning values to the Request object.
     *
     * @throws Zend_Controller_Router_Exception
     * @return Zend_Controller_Request_Abstract Request object
     */
    public function route(Zend_Controller_Request_Abstract $request)
    {

        if (!$request instanceof Zend_Controller_Request_Http) {
            throw new Zend_Controller_Router_Exception('Zend_Controller_Router_Rewrite requires a Zend_Controller_Request_Http-based request object');
        }

        if ($this->_useDefaultRoutes) {
            $this->addDefaultRoutes();
        }

        $pathInfo = $request->getPathInfo();
        $method = strtolower($_SERVER['REQUEST_METHOD']);
        
        // patch for AJAX request that wants to simulates REST
        // some browser can't use HTTP verbs other than GET/POST
        // so Javascript framework such as Prototype uses a POST
        // request with a _method parameter containing the name
        // of the HTTP Verb.
        if($method==='post'){
            $_m = $request->getParam('_method',null);
            if($_m) $method = strtolower($_m);
        }

        /** Find the matching route */
        foreach (array_reverse($this->_routes) as $name => $route) {
            $routeMethod = $route->getDefault('method');
            if(!$routeMethod) $routeMethod = 'get';
            if (($params = $route->match($pathInfo)) && $routeMethod===$method) {
                $this->_setRequestParams($request, $params);
                $this->_currentRoute = $name;
                break;
            }
        }

        return $request;

    }    
}